<template>
  <div class="PictureModule">
    <el-card
      class="box-card Picture-card mb-[8px]"
      shadow="never"
      v-for="(item, index) in pictureData"
      :key="index"
    >
      <template #header>
        <div class="card-header flex justify-between items-center h-[48px]">
          <div>
            {{ item.label
            }}<span v-if="item.image_type == 3" class="text-red-500 text-lg">*</span>
          </div>
          <div class="header-handle">
            <el-button
              link
              type="primary"
              :disabled="disabled"
              @click="handleEmpty(item.image_type, index)"
              >清空</el-button
            >
            <el-button
              v-if="item.image_type == 1"
              :disabled="disabled"
              @click="copyPic(item.image_type, 3)"
              >复制产品图片</el-button
            >
            <el-button
              v-if="item.image_type != 4 && item.image_type != 1"
              :disabled="disabled"
              @click="copyPic(item.image_type, 1)"
              >复制橱窗图</el-button
            >
            <el-select
              v-model="pictureData[index].image_source"
              v-if="item.image_type != 4"
              clearable
              class="m-2 !w-[160px]"
              placeholder="请选择"
              :disabled="disabled"
            >
              <el-option
                v-for="item in options['gallery.GoodsSkuGalleryContents']?.[0]
                  .imageSourceText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button
              v-if="item.image_type != 4"
              :disabled="disabled"
              @click="handleOpen(ExternalUrlRef, item.image_type)"
              >添加外部URL</el-button
            >
            <el-button
              :disabled="disabled"
              @click="
                handleOpen(
                  item.image_type === 4 ? videoRef : nativeRef,
                  item.image_type,
                  item.image_source
                )
              "
              >本地上传</el-button
            >

            <el-dropdown
              trigger="click"
              placement="bottom-start"
              @command="handleBatch($event, item)"
              v-if="item.image_type != 4"
            >
              <el-button class="m-2" :disabled="disabled">
                批量操作
                <i
                  style="font-size: 10px !important"
                  class="dk-iconfont icon-ArrowDown"
                />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-for="(item, index) in batchOptions"
                    :key="index"
                    :command="item.value"
                    >{{ item.label }}</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              v-if="item.image_type != 4 && id"
              @click="handleImageDownload(item)"
              >图片下载</el-button
            >
          </div>
        </div>
      </template>
      <PictureList
        v-model="item.values"
        :imageType="item.image_type"
        :imageSource="item.image_source"
        :isMainPic="isMainPic"
        :currentIndex="props.currentIndex"
      >
      </PictureList>
      <div class="text-xs text-gray-400" v-if="item.image_type == 2">
        <p>
          <svg-icon icon-class="hint_line" class="inline-block" />
          eBay最多支持12张图片，速卖通6张，Lazada8张，生成草稿时将自动按顺序取相应数量图片
        </p>
        <p>
          单个图片大小不超过2M，支持jpg，png，jpeg | 图片质量要清晰，不能虚化 |
          选择添加后，可批量添加，按序填充
        </p>
      </div>
      <div class="text-xs text-gray-400" v-if="item.image_type == 3">
        <svg-icon icon-class="hint_line" class="inline-block" />
        单个图片大小不超过2M，支持jpg，png，jpeg | 图片质量要清晰，不能虚化 |
        选择添加后，可批量添加，按序填充
      </div>
    </el-card>
  </div>
  <NativeUpload
    ref="nativeRef"
    @uploadFile="uploadFile"
    :customTag="props.customTag"
  ></NativeUpload>
  <VideoUpload
    ref="videoRef"
    @uploadFile="uploadFile"
    :customTag="props.customTag"
  ></VideoUpload>
  <ExternalUrl ref="ExternalUrlRef" @uploadFile="uploadFile" :customTag="props.customTag">
  </ExternalUrl>
  <batchUpdateImagetype
    ref="batchUpdateImagetypeRef"
    :options="options['gallery.GoodsSkuGalleryContents']?.[0].imageForText"
    @edit="handleBatchUpdateImagetype"
  ></batchUpdateImagetype>
  <batchImageTransfer
    ref="batchImageTransferRef"
    :imageTypeOptions="options['gallery.GoodsSkuGalleryContents']?.[0].imageTypeText"
    @edit="handleUpdateTransfer"
    :customTag="props.customTag"
  ></batchImageTransfer>
  <BatchImageDownload ref="batchImageDownloadRef" :gallery_id="id"></BatchImageDownload>
</template>

<script setup name="Module">
import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick, reactive, toRaw } from "vue";
import PictureList from "./List.vue";
import NativeUpload from "./NativeUpload.vue";
import VideoUpload from "./VideoUpload.vue";
import ExternalUrl from "./ExternalUrl.vue";
import batchUpdateImagetype from "@/components/Dialog/batchUpdateImagetype/index.vue";
import batchImageTransfer from "@/components/Dialog/batchImageTransfer/index.vue";
import BatchImageDownload from "@/components/Dialog/batchImageDownload/index.vue";

let options = reactive(inject("options"));
let handleType = reactive(inject("handleType"));
let formData = reactive(inject("form"));
let galleryList = reactive(inject("galleryList"));

const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  customTag: {
    type: String,
    default: () => "",
  },
  currentIndex: {
    type: Number,
  },
  customIndex: {
    type: Number,
  },
  id: {
    type: [Number, String],
    default: "",
  },
});

const { id } = toRefs(props);

const batchOptions = [
  {
    label: "批量维护类型",
    value: "MaintenancType",
  },
  {
    label: "批量图片迁移",
    value: "ImageTransfer",
  },
];

const disabled = computed(() => {
  return (
    handleType.value == "view" ||
    (handleType.value == "edit" &&
      !(window.BTN_AUTH || []).includes("/goods/task/product/picture-info"))
  );
});

const pictureData = computed({
  get: () => {
    options.value["gallery.GoodsSkuGalleryContents"]?.[0].imageTypeText.forEach(
      (element, e) => {
        props.modelValue &&
          props.modelValue.forEach((item, i) => {
            if (item.image_type == element.value) {
              item.label = element.label;
            }
          });
      }
    );
    return props.modelValue;
  },
  set: (val) => {
    emit("update:modelValue", val);
  },
});

let isMainPic = ref(false);
const nativeRef = ref(null);
const ExternalUrlRef = ref(null);
const videoRef = ref(null);
// 打开弹窗
const handleOpen = (ref, imageType, imageSource) => {
  nextTick(() => {
    ref.open(imageType, imageSource);
  });
};
// 设置主属性图
const changeMain = () => {
  let main = pictureData.value.filter((item) => item.image_type == 1);
  let mainList = main && main[0].values.filter((ma) => ma.is_main);
};

const handleEmpty = (type, index) => {
  ElMessageBox.confirm("是否清空当前类型的图片?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (handleType.value == "edit") {
      pictureData.value[index].values.forEach((i) => {
        i.delete = 1;
      });
      if (props.customIndex == 0 && type == 3) {
        formData.value.goods_sku[props.currentIndex].goods_sku_attr_img.forEach((i) => {
          i.delete = 1;
        });
      }
    } else {
      pictureData.value[index].values = [];
      if (props.customIndex == 0 && type == 3) {
        formData.value.goods_sku[props.currentIndex].goods_sku_attr_img = [];
      }
    }
  });
};
const uploadFile = (fileList, imageType) => {
  nextTick(() => {
    let currentValues = [];
    pictureData.value.forEach((item) => {
      if (item.image_type === imageType) {
        item.values.push(...fileList);
        currentValues.push(
          ...item.values.map((v) => {
            return {
              img_url: v.image_link,
              delete: v.delete,
            };
          })
        );
      }
    });
    // 标签第一项同步属性图
    if (props.customIndex == 0 && imageType == 3) {
      const attrIndex = currentValues.findIndex((i) => !i.delete);
      if (handleType.value == "edit") {
        formData.value.goods_sku[props.currentIndex].goods_sku_attr_img.forEach((i) => {
          i.delete = 1;
        });
        formData.value.goods_sku[props.currentIndex].goods_sku_attr_img.push(
          ...currentValues
        );
        if (!formData.value.goods_sku[props.currentIndex].attr_img) {
          formData.value.goods_sku[props.currentIndex].attr_img =
            currentValues[attrIndex].img_url || "";
        }
      } else {
        formData.value.goods_sku[props.currentIndex].goods_sku_attr_img =
          currentValues || [];
        if (!formData.value.goods_sku[props.currentIndex].attr_img) {
          formData.value.goods_sku[props.currentIndex].attr_img =
            currentValues[attrIndex].img_url || "";
        }
      }
    }
    if (imageType == 3) {
      changeMain();
    }
  });
};
// 赋值橱窗图
const copyPic = (type, copyType) => {
  let picList = pictureData.value.filter((item) => item.image_type == copyType);
  if (picList[0].values.length == 0) return ElMessage.error(`请上传${picList[0].label}`);

  pictureData.value = pictureData.value.map((pic) => {
    if (pic.image_type == type) {
      const filerValues = picList[0].values.map((i) => {
        let copiedItem = JSON.parse(JSON.stringify(i));
        copiedItem.image_type = pic.image_type;
        delete copiedItem.id;
        return copiedItem;
      });
      pic.values.push(...filerValues);
    }
    return pic;
  });
};

// 批量维护类型
const batchUpdateImagetypeRef = ref();
const handleBatchUpdateType = (item) => {
  console.log(item);
  if (item.values.length == 0) {
    ElMessage.error("暂无可维护类型的图片,请先上传图片");
    return;
  }
  batchUpdateImagetypeRef.value.open(item);
};

// 批量修改类型
const handleBatchUpdateImagetype = (val) => {
  pictureData.value = pictureData.value.map((pic) => {
    if (pic.image_type == val.type) {
      pic.values = val.values;
    }
    return pic;
  });
};

// 批量图片迁移
const batchImageTransferRef = ref();
const handleBatchImageTransfer = (item) => {
  if (item.values.filter((i) => !i.delete).length == 0) {
    ElMessage.error("暂无可维护类型的图片,请先上传图片");
    return;
  }

  if (galleryList.value.filter((i) => !i.delete).length == 1) {
    ElMessage.error("当前只有一个标签,请先添加标签");
    return;
  }

  batchImageTransferRef.value.open(item);
};

const handleUpdateTransfer = () => {};

// 批量操作
const handleBatch = (value, item) => {
  if (value == "MaintenancType") {
    handleBatchUpdateType(item);
  } else if (value == "ImageTransfer") {
    handleBatchImageTransfer(item);
  }
};

// 图片下载
const batchImageDownloadRef = ref();
const handleImageDownload = (item) => {
  if (item.values.filter((i) => !i.delete).length == 0) {
    ElMessage.error("暂无可下载的图片,请先上传图片");
    return;
  }
  batchImageDownloadRef.value.open(item);
};
</script>

<style lang="scss" scoped>
.Picture-card {
  :deep(.el-card__header) {
    border-bottom: 1px dashed #e6e7e9;
  }
}
:deep(.el-card__body) {
  margin: 0 10px;
}
:deep(.el-card__header) {
  padding: 0;
  margin: 0 20px;
}
</style>
